package yxy.game.pm2.module.friend;

import java.util.ArrayList;
import java.util.Collection;

import org.redisson.api.RScoredSortedSet;

import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

/** 好友不满的玩家列表 */
public class NeedFriendList extends BaseGameRedisBean {
	// func===========================================================================
	private int clusterId; //专服id
	private int areaGroupId; //战区内id

	public int getClusterId() {
		return clusterId;
	}

	public void setClusterId(int clusterId) {
		this.clusterId = clusterId;
	}

	public int getAreaGroupId() {
		return areaGroupId;
	}

	public void setAreaGroupId(int areaGroupId) {
		this.areaGroupId = areaGroupId;
	}

	public NeedFriendList (int areaGroupId) {
		setAreaGroupId(areaGroupId);
	}

	// redis==========================================================================

	static public String key(int areaGroupId) {
		return String.format("FRIEND:%s:NEEDLIST", areaGroupId);
	}

	static private RScoredSortedSet<String> touch(int areaGroupId) throws RedisException {
		return RedisManager.client(redis()).getScoredSortedSet(key(areaGroupId));
	}

	/** 获得推荐 */
	public Collection<String> recommend() {
		try {
			return touch(getAreaGroupId()).valueRangeReversed(0, 100);
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	public void update(FriendModule friendModule) {
		int vacant = friendModule.vacant();
		try {
			PlayerBean playerBean = PlayerBean.get(friendModule.getPlayerCode());
			ServerBean serverBean = ServerBean.get(playerBean.getServerId());
			AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
			int areaGroupId = areaBean.getGroupId();

			if (tryLock()) {
				if (vacant <= 0) {
					touch(areaGroupId).remove(friendModule.getPlayerCode());
					return;
				}
				long score = System.currentTimeMillis();
				touch(areaGroupId).add(score, friendModule.getPlayerCode());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			unlock();
		}
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getAreaGroupId()));
	}

}
